package com.hut.blog.controller;

import com.hut.blog.constant.Constants;
import com.hut.blog.model.Result;
import com.hut.blog.model.UserInfo;
import com.hut.blog.service.UserService;
import com.hut.blog.utils.JwtUntil;
import com.hut.blog.utils.Md5;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    /**
     * 用户登录
     */
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName,String password) {
        //打印传递参数的日志
        log.info("UserController#login接收参数: username:{}, password:{}", userName, password);
        //校验参数是否合法
        if(!StringUtils.hasLength(userName) ||!StringUtils.hasLength(password)) {
            return Result.fail("账号或者密码不合法");
        }
        //账户不存在
        UserInfo userInfo = userService.selectByName(userName);
        if(userInfo == null) {
            return Result.fail("用户不存在");
        }
        //密码错误
        if (!Md5.verify(password, userInfo.getPassword())){
            log.error("密码错误");
            return Result.fail("密码错误");
        }
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USER_NAME,userInfo.getUserName());
        String token = JwtUntil.genJwtToken(claim);
        log.info("UserController#login 返回结果token:{}",token);
        return Result.success(token);
    }

    /**
     * 根据token中的信息拿到用户Id
     * @param request
     * @return
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        //打印日志
        log.info("获取用户信息");
        //从headr中获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取登录用户Id
        Integer userId = JwtUntil.getIdByToken(token);
        if(userId == null) {
            //用户未登录
            return null;
        }
        UserInfo userInfo = userService.selectById(userId);
        return userInfo;
    }

    /**'
     * 根据blog信息获取到作者Id从而获取作者的信息
     * @param blogId
     * @return
     */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        UserInfo userInfo = userService.selectByBolgId(blogId);
        return userInfo;
    }
}
